<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form label-width="100px" ref="searchRef" :model="queryParams">
        <el-row>
          <el-col :span="6">
            <el-form-item label="机构名称" prop="name">
              <ns-input v-model="queryParams.name" clearable placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="机构状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择机构状态"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="授权状态" prop="ruleStatus">
              <el-select
                v-model="queryParams.ruleStatus"
                placeholder="请选择授权状态"
                clearable
                class="!w-240px"
              >
                <el-option label="已授权" :value="1" />
                <el-option label="未授权" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="searchReset" plain>重置</el-button>
            <el-button @click="search" plain>搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button type="primary" @click="handleAuthorization(1, 1)"> 授权上线权限</el-button>
        <el-button type="primary" @click="handleAuthorization(1, 2)"> 授权下线权限</el-button>
        <el-button plain @click="handleAuthorization(0, 1)"> 回收上线权限</el-button>
        <el-button plain @click="handleAuthorization(0, 2)"> 回收下线权限</el-button>
      </el-form-item>
      <div style="width: 100%; height: 600px">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2
              v-model:expanded-row-keys="expandedRowKeys"
              style="width: 100%"
              :columns="columns"
              :data="list"
              :width="width"
              expand-column-key="name"
              row-key="id"
              :height="height"
              fixed
              layout="fixed"
            />
          </template>
        </el-auto-resizer>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import * as api from '@/api/dataAuthorization'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ElSelect, ElOption, ElMessageBox, ElCheckbox } from 'element-plus'
import type { FunctionalComponent } from 'vue'
import type { CheckboxValueType, Column } from 'element-plus'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute()
const searchRef = ref()
const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据
const queryParams = ref({
  name: '',
  status: '',
  ruleStatus: ''
})

const searchReset = () => {
  searchRef.value.resetFields()
  search()
}

const multipleSelection = ref([])

const expandedRowKeys = ref<string[]>([])

type SelectionCellProps = {
  value: boolean
  intermediate?: boolean
  onChange: (value: CheckboxValueType) => void
}
const SelectionCell: FunctionalComponent<SelectionCellProps> = ({
  value,
  intermediate = false,
  onChange
}) => {
  return <ElCheckbox onChange={onChange} modelValue={value} indeterminate={intermediate} />
}

// 找出树形中checked为true的项
function findCheckedItems(tree) {
  let checkedItems = []

  function traverse(node) {
    if (node.checked) {
      checkedItems.push(node)
    }
    if (node.children && node.children.length > 0) {
      node.children.forEach((child) => traverse(child))
    }
  }

  tree.forEach((node) => traverse(node))
  return checkedItems
}

// 设置所有节点checked
function setAllCheckedStatus(tree, bool) {
  function traverse(node) {
    node.checked = bool // 设置当前节点的 checked 为 true

    // 如果当前节点有子节点数组，则遍历每个子节点
    if (Array.isArray(node.children) && node.children.length > 0) {
      node.children.forEach((child) => traverse(child)) // 递归调用 traverse
    }
  }

  // 对树中的每个根节点调用 traverse
  tree.forEach((node) => traverse(node))
}

const columns = [
  {
    key: 'selection',
    width: 100,
    cellRenderer: ({ rowData }) => {
      const _data = unref(list)
      const onChange = (value: CheckboxValueType) => {
        setAllCheckedStatus([rowData], value)
        multipleSelection.value = findCheckedItems(_data)
      }
      return <SelectionCell value={rowData.checked} onChange={onChange} />
    },

    headerCellRenderer: () => {
      const _data = unref(list)
      const onChange = (value: CheckboxValueType) => {
        setAllCheckedStatus(list.value, value)
        multipleSelection.value = findCheckedItems(list.value)
      }
      const allSelected = _data.every((row) => row.checked)
      const containsChecked = _data.some((row) => row.checked)

      return (
        <SelectionCell
          value={allSelected}
          intermediate={containsChecked && !allSelected}
          onChange={onChange}
        />
      )
    }
  },
  {
    key: 'name',
    dataKey: 'name',
    title: '机构名称',
    width: 300
  },
  {
    key: 'ruleStatusName',
    dataKey: 'ruleStatusName',
    title: '上线权限状态',
    width: 300,
    align: 'center',
    cellRenderer: ({ rowData }) => (
      <>
        {rowData.ruleStatus == 1 ? (
          <div>{rowData.radius == 2 ? <div>本机构及下级机构</div> : <div>本机构</div>}</div>
        ) : (
          <div>未授权</div>
        )}
      </>
    )
  },
  {
    key: 'ruleStatusName2',
    dataKey: 'ruleStatusName2',
    title: '下线权限状态',
    width: 300,
    align: 'center',
    cellRenderer: ({ rowData }) => (
      <>
        {rowData.ruleStatus2 == 1 ? (
          <div>{rowData.radius2 == 2 ? <div>本机构及下级机构</div> : <div>本机构</div>}</div>
        ) : (
          <div>未授权</div>
        )}
      </>
    )
  },
  {
    key: 'status',
    dataKey: 'status',
    title: '状态',
    width: 300,
    align: 'center',
    cellRenderer: ({ rowData }) => (
      <>
        <dict-tag type={DICT_TYPE.COMMON_STATUS} value={rowData.status} />
      </>
    )
  }
]

const search = () => {
  getList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const { data } = await api.deptTree({
      ...queryParams.value,
      userId: route.query.id,
      dateStatus: 1
    })
    list.value = data
    console.log('data', data)
  } finally {
    loading.value = false
    setAllCheckedStatus(list.value, false)
  }
}

const radius = ref('1')

const selectOptions = () => [
  h(ElOption, { label: '本机构', value: '1' }),
  h(ElOption, { label: '本机构以及下级机构', value: '2' })
]

const select = () =>
  h('div', [
    h('span', '授权范围：'),
    h(
      ElSelect,
      {
        modelValue: radius.value,
        placeholder: '请选择',
        'onUpdate:modelValue': (val) => {
          radius.value = val
        },
        style: 'width:300px'
      },
      selectOptions
    )
  ])

//available: 0-回收权限 1-授权
// type：1-上线 2-下线
const handleAuthorization = async (available, type) => {
  if (multipleSelection.value.length == 0) {
    message.warning('请选择授权机构')
    return
  }

  var params
  if (available === 1) {
    console.log(multipleSelection.value, 1231)
    ElMessageBox({
      title: '权限授权',
      message: select,
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(async () => {
      params = multipleSelection.value?.map((item: any) => {
        return {
          userId: route.query.id,
          relevancyId: item.id,
          relevancyType: '1',
          available: type == 1 ? available : item.ruleStatus,
          available2: type == 2 ? available : item.ruleStatus2,
          radius: type == 1 ? radius.value : item.radius,
          radius2: type == 2 ? radius.value : item.radius2
        }
      })
      const data = await api.dataAuthorizationUpdate(params)
      console.log('data', data)
      if (data) {
        getList()
        message.success('操作成功')
      }
    })
  } else {
    params = multipleSelection.value?.map((item: any) => {
      return {
        userId: route.query.id,
        relevancyId: item.id,
        relevancyType: '1',
        available: type == 1 ? available : item.ruleStatus,
        available2: type == 2 ? available : item.ruleStatus2,
        radius: item.radius,
        radius2: item.radius2
      }
    })
    const data = await api.dataAuthorizationUpdate(params)
    console.log('data', data)
    if (data) {
      getList()
      message.success('操作成功')
    }
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
